package com.tkjt.pms.modules.repos.controller;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tkjt.pms.modules.common.mapper.PMSCommonMapper;
import com.tkjt.pms.modules.kpiadmin.vo.HeadConditionVO;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tkjt.pms.common.entity.TkIndexValueImport;
import com.tkjt.pms.modules.common.service.TkDataConfigService;
import com.tkjt.pms.modules.common.service.TkIndexValueImportService;
import com.tkjt.pms.modules.kpiadmin.service.KpiAdminService;
import com.tkjt.pms.modules.kpiadmin.vo.DatagridVO;
import com.tkjt.pms.modules.repos.service.IndexRepoService;
import com.tkjt.pms.modules.repos.thread.ConfirmDataThread;
import com.tkjt.pms.modules.repos.thread.ImportDataThread;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/pms/repos/dataMgr")
public class DataMgrController {

    @Autowired
    KpiAdminService kpiAdminService;
    @Autowired
    private IndexRepoService indexRepoService;
    @Autowired
    private TkDataConfigService tkDataConfigService;
    @Autowired
    TkIndexValueImportService tkIndexValueImportService;
    @Autowired
    PMSCommonMapper commonMapper;
    /**
     * 目标实际值导入列表-列表条件
     * 表头信息
     * @return
     */
    @RequestMapping("goalValueConditions")
    public Result<?> kaFillConditions(@RequestBody DatagridVO datagridVO){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        List<Map<String,Object>> indexPeriods = commonMapper.getDictItemByDictCode("yearMonth");
        HeadConditionVO headConditionVO = new HeadConditionVO();
        headConditionVO.setIndexPeriods(indexPeriods);
        List<Map<String,Object>> tabHeader = new ArrayList<>();
        Map<String,Object> codeMap = new HashMap<>();
        codeMap.put("name","指标名称");
        codeMap.put("code","indexName");
        tabHeader.add(codeMap);
        codeMap = new HashMap<>();
        codeMap.put("name","指标编码");
        codeMap.put("code","indexCode");
        codeMap.put("isShow",false);
        tabHeader.add(codeMap);
        codeMap = new HashMap<>();
        codeMap.put("name","指标值名称");
        codeMap.put("code","indexValueName");
        tabHeader.add(codeMap);
        codeMap = new HashMap<>();
        codeMap.put("name","指标值编码");
        codeMap.put("code","indexValueCode");
        codeMap.put("isShow",false);
        tabHeader.add(codeMap);
        try {
            List<Map<String,Object>> indexGroups = kpiAdminService.indexGroupConditions(loginUser,tabHeader,null,datagridVO.getIndexYearMonth());
            headConditionVO.setIndexGroup(indexGroups);
            return Result.ok(indexGroups);
        }catch (Exception e){e.printStackTrace();
            return Result.error("获取数据异常");
        }

    }
    /**
     * *目标实际值导入列表查询
     * *@return
     */
    @RequestMapping("goalValueDatagrid")
    public Result<?> goalValueDatagrid(@RequestBody DatagridVO datagridVO){
        try {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if(loginUser==null) {
                return Result.error("用户非法！");
            }
            datagridVO.setIndexValueEdit("1");
            String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
            try {
                return indexRepoService.kaFillDatagrid(datagridVO,null,dataType);
            }catch (Exception e){e.printStackTrace();
                return Result.error("获取数据异常");
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return Result.error("获取数据异常");
        }
    }

    /**
     * *导入数据
     * *@return
     */
    @RequestMapping("goalValueImport")
    public Result<?> goalValueImport(@RequestParam("file") MultipartFile file, String indexYearMonth){
        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(2);
            params.setNeedSave(false);
            String fileName = file.getOriginalFilename();
            File newFile = new File(fileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if(loginUser==null) {
                return Result.error("用户非法！");
            }
            String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
            if(StringUtils.isEmpty(indexYearMonth)){
                return Result.error("参数缺失！");
            }
            new Thread(new ImportDataThread(fileName, newFile, params, dataType,indexYearMonth,indexRepoService)).start();
            return Result.ok("正在导入数据");
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return Result.error("获取数据异常");
        }
    }

    /**
     * *确认数据
     * *@return
     */
    @RequestMapping("goalValueConfirm")
    public Result<?> goalValueConfirm(@RequestBody DatagridVO datagridVO){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
        String indexYearMonth = datagridVO.getIndexYearMonth();
        if(StringUtils.isEmpty(indexYearMonth)){
            return Result.error("参数缺失！");
        }
        QueryWrapper<TkIndexValueImport> importQueryWrapper = new QueryWrapper<>();
        importQueryWrapper.lambda().eq(TkIndexValueImport::getIndexYearMonth,indexYearMonth);
        importQueryWrapper.lambda().eq(TkIndexValueImport::getDataType,dataType);
        try {

            int count = tkIndexValueImportService.count(importQueryWrapper);
            if(count == 0){
                return Result.error("请先导入数据！");
            }
            new Thread(new ConfirmDataThread(dataType,indexYearMonth, indexRepoService, tkIndexValueImportService,importQueryWrapper)).start();
            return Result.ok("正在同步数据");
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return Result.error("获取数据异常");
        }
    }
    /**
     * *单条数据修改
     * @return
     */
    @RequestMapping("goalValueModify")
    public Result<?> goalValueModify(@RequestBody DatagridVO datagridVO){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
        try {
            return indexRepoService.indexValueDataSave(datagridVO,dataType);
        }catch (Exception e){e.printStackTrace();
            return Result.error("获取数据异常");
        }

    }
}
